package com.ay.weixin.fdc.front.blog.event;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;

import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.boss.blog.db.BlogContentDao;
import com.ay.weixin.fdc.boss.blog.db.BlogDao;
import com.ay.weixin.fdc.boss.blog.domain.Blog;
import com.ay.weixin.fdc.boss.blog.domain.BlogContent;
import com.ay.weixin.fdc.boss.user.db.UserDao;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;

public class BlogEvt extends Event {

	private BlogDao blog_dao;
	private BlogContentDao content_dao;
	private UserDao user_dao;
	
	@Override
	public void init_property() throws Exception {
		blog_dao=Container.get(BlogDao.class);
		user_dao=Container.get(UserDao.class);
		content_dao=Container.get(BlogContentDao.class);
		
	}

	@Override
	public String default_handling_path() {
		return "/blog/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id=el.queryPathInt(1);
		
		if(!el.getBool("is_weixin")&&ProjectConfig._bool(wxproject_id,"weixin_only")){
			el.text("invalid visit");
			return;
		}
		UserBasic user=el.getSessionAttr("user",UserBasic.class);
		if(el.queryPathCheck(2, "list")){
			list(el,wxproject_id);
		}else if(el.queryPathCheck(2, "visit")){
			try {
				blog(el,wxproject_id);
				return;
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}else{
			try {
				blog(el,wxproject_id);
				return;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		list(el,wxproject_id);
	}
	
	
	private void blog(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		long uid=el.getLong("uid");
		long sa_id=el.getLong("sa_id");
		
		
		Blog sa=blog_dao.getById(sa_id);
		
		if(sa==null){
			System.out.println("sa is null");
			list(el,wxproject_id);
			return;
		}
		
		List<BlogContent> content_list=null;
		content_list=content_dao.getBySAId(sa_id);
		el.setAttr("content_list", content_list);
		el.setAttr("sa", sa);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/blog/"+sa.getTemplate()+"/index.vm");
	}
	
	private void list(EventLoader el,long wxproject_id) throws IOException, ServletException{
		List<Blog> salist=null;
		try {
			salist=blog_dao.getAllTop50(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		el.setAttr("status_list",Blog.STATUS.values());
		el.setAttr("salist",salist);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/blog/index.vm");
	}

}
